package com.jin.webvideo.service;

import com.jin.webvideo.base.util.CollectionsUtil;
import com.jin.webvideo.mapper.ConfigMapper;
import com.jin.webvideo.util.base.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ConfigService {
    @Autowired
    private ConfigMapper configMapper;

    /**
     * notice接口
     * @return
     */
    @Cacheable(cacheNames = "configCache", key = "'sysConfig-notice'")
    public String notice(){
        return configMapper.findValByGroupAndId("sysConfig", "notice");
    }

    /**
     * 根据groupid获取配置
     * @param groupid
     * @return
     */
    @Cacheable(cacheNames = "configCache", key = "#groupid + '-*'")
    public Map<String, String> configMapByGroupId(String groupid){
        List<Map<String, String>> list = configMapper.findByGroup(groupid);
        return CollectionsUtil.convert(list, "attrKey", "attrVal");
    }

    /**
     * 根据groupid 和 attrId 获取配置
     * @param groupid
     * @param attrId
     * @return
     */
    public String configByGroupIdAndAttrid(String groupid, String attrId){
        Map<String,String> map = configMapByGroupId(groupid);
        return map.get(attrId);
    }

    /**
     * 检验推荐码
     * @param activeKey
     * @return
     */
    public boolean validActiveKey(String activeKey){
        String temp = configMapper.findValByGroupAndId("activeKey", activeKey);
        if (StringUtil.isEmpty(temp)){
            return false;
        }
        String[] arr = temp.split("\\|");
        int max = Integer.valueOf(arr[1]);
        int num = Integer.valueOf(arr[2]);
        if (max <= num){
            return false;
        }
        String val = String.format("%s|%d|%d", arr[0], max, ++num);
        return configMapper.updateValByGroupAndId("activeKey", activeKey, val) == 1;
    }
}
